import json
from flask import Flask, request
import uuid
import model
import utils
import chat

app = Flask(__name__)

@app.route("/update-link", methods=["POST"])
def upload_link():
    unique_embedding_id = str(uuid.uuid4())
    data = json.loads(request.data)
    print(data)
    url_link = data["link"]
    source = "link: " + url_link

    text = utils.extract_text_from_link(url_link)
    documents = utils.get_text_documents(text, source)

    model.update_embedding([documents], source, unique_embedding_id)

    return {
        "message": "链接分析完成",
        "unique_embedding_id": unique_embedding_id
    }


@app.route("/upload-files", methods=["POST"])
def upload_files():
    if "file" not in request.files:
        return "No file uploaded", 400
    
    unique_embedding_id = str(uuid.uuid4())
    file = request.files["file"]
    source = "file: " + file.filename

    documents = utils.get_files_documents(file)

    model.update_embedding(documents, source, unique_embedding_id)

    return {
        "message": "文档分析完成",
        "unique_embedding_id": unique_embedding_id
    }

@app.route("/chat", methods=["POST"])
def chat_with_type():
    data = json.loads(request.data)
    print(data)
    query = data.get("query", "")
    chat_type = data.get("chat_type", "")
    unique_chat_id = data.get("unique_chat_id", "")
    unique_embedding_id = data.get("unique_embedding_id", "")
    return chat.generate_response(query, chat_type, unique_chat_id, unique_embedding_id)

@app.route("/save-chat", methods=["POST"])
def save_chat():
    data = json.loads(request.data)
    print(data)
    unique_chat_id = data.get("unique_chat_id", "")
    return chat.save_chat(unique_chat_id)

@app.route("/get-all-saved-chats", methods=["POST"])
def get_save_chat():
    data = json.loads(request.data)
    print(data)
    return chat.get_all_saved_chats()
